<template>
  <view>
    <view @click="show = true">
      <slot></slot>
    </view>
    <up-action-sheet
      :actions="actions"
      :closeOnClickOverlay="true"
      :closeOnClickAction="true"
      :show="show"
      cancelText="取消"
      @select="onSelect"
      @close="show = false" />
  </view>
</template>

<script lang="ts" setup>
  import { defineEmits, ref } from 'vue'
  import { apiUrl } from '@/configs'

  type AssetAction = {
    name: string;
    type: 'album' | 'camera';
  }

  type UploadResult = {
    url: string;
    fullurl: string;
  }

  const emit = defineEmits<{
    (e: 'success', data: UploadResult): void
    (e: 'fail'): void
  }>()

  const actions = ref<AssetAction[]>([
    { name: '相册', type: 'album' },
    { name: '相机', type: 'camera' },
  ])
  const show = ref(false)

  const onSelect = (action: AssetAction) => {
    const cur = actions.value.find((item) => item.type === action.type)

    if (!cur) return

    uni.chooseImage({
      count: 1,
      sourceType: [cur.type],
      success: (chooseImageRes) => {
        uni.showLoading({ mask: true })
        const tempFilePaths = chooseImageRes.tempFilePaths

        uni.uploadFile({
          url: `${apiUrl}/upload/index`,
          filePath: tempFilePaths[0],
          name: 'file',
          success: (uploadFileRes) => {
            try {
              const ret = JSON.parse(uploadFileRes.data)
              console.log('上传结果：', ret)
              if (ret.code === 1) {
                console.log(ret.data)
                emit('success', ret.data as UploadResult)
              } else {
                uni.showToast({ title: '上传失败', icon: 'none' })
                emit('fail')
              }
            } catch (e) {
              uni.showToast({ title: '上传失败', icon: 'none' })
              emit('fail')
            }
          },
          fail: (uploadFileError) => {
            console.log(uploadFileError)
            uni.showToast({ title: '上传失败', icon: 'none' })
            emit('fail')
          },
          complete: () => {
            uni.hideLoading()
          },
        })
      },
    })
  }
</script>

<style lang="scss">

</style>
